package com.quanyan.place.service.impl;

import java.awt.Rectangle;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apiresp.*;
import com.quanyan.place.enums.PayTypeEnum;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.*;

import com.quanyan.place.utils.PlaceUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import sms.SmsApi;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.PlatformTypeEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.UUIDUtils;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.biz.SmsService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.apireq.ReqOrderHistory;
import com.quanyan.place.entity.apireq.ReqPlaceTicket;
import com.quanyan.place.entity.apireq.ReqTicketPay;
import com.quanyan.place.entity.apireq.ReqTicketSale;
import com.quanyan.place.entity.vo.PlacePrintVo;
import com.quanyan.place.entity.vo.ReqPlaceMemberSearch;
import com.quanyan.place.utils.PlaceOrderUtil;

/**
 * Created by youxiaojia on 2016/9/21.
 */
@Service("placeTicketService")
public class PlaceTicketServiceImpl implements PlaceTicketService {
    private static final Logger logger = LoggerFactory.getLogger(PlaceTicketServiceImpl.class);
    @Autowired
    private TbBizPlaceAttachMapper tbBizPlaceAttachMapper;

    @Autowired
    private TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;

    @Autowired
    private TbBizPlaceMemberMapper tbBizPlaceMemberMapper;

    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;

    @Autowired
    private TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    private TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

    @Autowired
    private TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

    @Autowired
    private TbPlaceTicketStatisticsMapper tbPlaceTicketStatisticsMapper;

    @Autowired
    private TbPlaceTicketStatisticsPlusMapper tbPlaceTicketStatisticsPlusMapper;

    @Autowired
    private TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;

    @Autowired
    IBaseService iBaseService;

    @Autowired
    private TbBizPlaceMemberCardTypeTicketMapper tbBizPlaceMemberCardTypeTicketMapper;

    @Autowired
    PlaceMemberService placeMemberService;

    @Autowired
    SmsService smsService;

    @Autowired
    private TbBizPlaceMemberCardTypeMapper tbBizPlaceMemberCardTypeMapper;
    @Autowired
    private TbBizPlaceMapper tbBizPlaceMapper;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    BaseService baseService;

    @Autowired
    PlaceOrderUtilService placeOrderUtilService;

    @Autowired
    com.quanyan.place.biz.SmsService  placeSmsService;

    @Autowired
    CacheService cacheService;
    @Autowired
    PosUnionPayMapper posUnionPayMapper;
    @Autowired
    TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;
    @Autowired
    TbCommonParameterMapper tbCommonParameterMapper;
    
    @Autowired
    private VPlaceMemberMapper vPlaceMemberMapper;

    /**
     * 添加门票销售
     *
     * @param reqPlaceTicket
     * @return
     */
    @Override
    public APIResponse insertPlaceTicket(ReqPlaceTicket reqPlaceTicket) {
        if (reqPlaceTicket == null) {
            return APIResponse.returnFail("reqPlaceTicket为空！");
        }
        TbPlaceTicketSalePlan tbPlaceTicketSalePlan = new TbPlaceTicketSalePlan();
        tbPlaceTicketSalePlan.setPlaceId(reqPlaceTicket.getPlaceId());
        tbPlaceTicketSalePlan.setTicketName(reqPlaceTicket.getTicketName());
        tbPlaceTicketSalePlan.setCategoryId(reqPlaceTicket.getCategoryId());
        tbPlaceTicketSalePlan.setStartWeek(reqPlaceTicket.getStartWeek());
        tbPlaceTicketSalePlan.setEndWeek(reqPlaceTicket.getEndWeek());
        tbPlaceTicketSalePlan.setPrice(reqPlaceTicket.getPrice());
        tbPlaceTicketSalePlan.setMemberPrice(reqPlaceTicket.getMemberPrice());
        tbPlaceTicketSalePlan.setLimitNum(reqPlaceTicket.getLimitNum());
        tbPlaceTicketSalePlan.setDescrible(reqPlaceTicket.getDescrible());
        tbPlaceTicketSalePlan.setCreateUid(reqPlaceTicket.getCreateUid());
        tbPlaceTicketSalePlan.setUpdateUid(reqPlaceTicket.getUpdateUid());
        tbPlaceTicketSalePlan.setIsSaleClient(reqPlaceTicket.getIsSaleClient());

        Date startTime = DateTimeUtils.convertString2Date("HH:mm:ss", reqPlaceTicket.getStartTime());
        Date endTime = DateTimeUtils.convertString2Date("HH:mm:ss", reqPlaceTicket.getEndTime());
        tbPlaceTicketSalePlan.setStartTime(startTime);
        tbPlaceTicketSalePlan.setEndTime(endTime);
        tbPlaceTicketSalePlan.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
        tbPlaceTicketSalePlan.setCreateTime(new Date());
        tbPlaceTicketSalePlan.setUpdateTime(new Date());
        tbPlaceTicketSalePlan.setStatus(PlaceConstants.PLACE_TICKET_STATUS_ENABLE);
        tbPlaceTicketSalePlan.setSaleNo(createSaleNo());
        //判断门票是否相交
        if (checkTimeAndWeek(reqPlaceTicket.getPlaceId(), reqPlaceTicket.getCategoryId(), startTime, endTime, reqPlaceTicket.getStartWeek(), reqPlaceTicket.getEndWeek(),null)) {
            return APIResponse.returnFail("存在有相交或包含关系的门票！");
        }
        int flag = tbPlaceTicketSalePlanMapper.insert(tbPlaceTicketSalePlan);
        if (flag == 1) {
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("添加门票失败");
        }
    }

    /**
     * 门票销售列表
     *
     * @param placeId
     * @param categoryId
     * @return
     */
    @Override
    public APIResponse<RespPlaceTicketSalePlanVo> queryPlaceTicketList(Integer placeId, Integer categoryId) {
        //获取场馆附属信息
        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = example.createCriteria();
        tbBizPlaceAttachCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);
        String startTime = null;
        String endTime = null;
        double offsetTime = PlaceConstants.PLACE_OFFSET_TIME;
        if (CollectionUtils.isNotEmpty(result)) {
            TbBizPlaceAttach tbBizPlaceAttach = result.get(0);
            /*if (tbBizPlaceAttach.getBusinessHourStart().compareTo(tbBizPlaceAttach.getHolidayBusinessHourStart()) >= 0) {
                startTime = tbBizPlaceAttach.getHolidayBusinessHourStart();
            } else {
                startTime = tbBizPlaceAttach.getBusinessHourStart();
            }

            if (tbBizPlaceAttach.getBusinessHourEnd().compareTo(tbBizPlaceAttach.getHolidayBusinessHourEnd()) >= 0) {
                endTime = tbBizPlaceAttach.getBusinessHourEnd();
            } else {
                endTime = tbBizPlaceAttach.getHolidayBusinessHourEnd();
            }*/
            startTime = tbBizPlaceAttach.getBusinessHourStart();
            endTime = tbBizPlaceAttach.getBusinessHourEnd();
        } else {
            logger.debug("该场馆没有可用的销售时段！");
            return APIResponse.returnSuccess();
        }
        RespPlaceTicketSalePlanVo respPlaceTicketSalePlanVo = new RespPlaceTicketSalePlanVo();
        //返回经营时段
        respPlaceTicketSalePlanVo.setTimeList(PlaceOrderUtil.getIntervalTimeList(startTime, endTime, (int)(offsetTime * 60)));
        TbPlaceTicketSalePlanExample tbPlaceTicketSalePlanExample = new TbPlaceTicketSalePlanExample();
        TbPlaceTicketSalePlanExample.Criteria tbPlaceTicketSalePlanCriteria = tbPlaceTicketSalePlanExample.createCriteria();
        if (!StringUtils.isEmpty(placeId)) {
            tbPlaceTicketSalePlanCriteria.andPlaceIdEqualTo(placeId);
        }
        if (!StringUtils.isEmpty(categoryId)) {
            tbPlaceTicketSalePlanCriteria.andCategoryIdEqualTo(categoryId);
        }
        tbPlaceTicketSalePlanCriteria.andIsEffectiveEqualTo(PlaceConstants.IS_EFFECTIVE_YES);
        tbPlaceTicketSalePlanCriteria.andStatusEqualTo(PlaceConstants.PLACE_TICKET_STATUS_ENABLE);
        List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlanList = tbPlaceTicketSalePlanMapper.selectByExample(tbPlaceTicketSalePlanExample);
        if (CollectionUtils.isEmpty(tbPlaceTicketSalePlanList)){
            logger.debug("没有门票销售计划！");
            return APIResponse.returnSuccess(respPlaceTicketSalePlanVo);
        }
        respPlaceTicketSalePlanVo.setPlaceTicketSalePlanList(tbPlaceTicketSalePlanList);
        return APIResponse.returnSuccess(respPlaceTicketSalePlanVo);
    }

    /**
     * 取消门票销售
     * @param tbPlaceTicketSalePlanId
     * @param uid
     * @return
     */
    @Override
    public APIResponse cancelPlaceTicketSale(Integer tbPlaceTicketSalePlanId,Integer uid) {
        TbPlaceTicketSalePlan tbPlaceTicketSalePlan = new TbPlaceTicketSalePlan();
        tbPlaceTicketSalePlan.setId(tbPlaceTicketSalePlanId);
        tbPlaceTicketSalePlan.setStatus(PlaceConstants.PLACE_TICKET_STATUS_DISABLE);
        tbPlaceTicketSalePlan.setUpdateUid(uid);
        tbPlaceTicketSalePlan.setUpdateTime(new Date());
        int flag = tbPlaceTicketSalePlanMapper.updateByPrimaryKeySelective(tbPlaceTicketSalePlan);
        return APIResponse.returnSuccess(flag==1?true:false);
    }

    /**
     * 根据门票id查询门票详情
     * @param tbPlaceTicketSalePlanId
     * @return
     */
    @Override
    public APIResponse getPlaceTicketSaleDetailById(Integer tbPlaceTicketSalePlanId) {
        TbPlaceTicketSalePlan tbPlaceTicketSalePlan = tbPlaceTicketSalePlanMapper.selectByPrimaryKey(tbPlaceTicketSalePlanId);
        if (StringUtils.isEmpty(tbPlaceTicketSalePlan)){
            return APIResponse.returnFail("没有此门票！");
        }
        return APIResponse.returnSuccess(tbPlaceTicketSalePlan);
    }

    /**
     * 编辑门票
     * @param reqPlaceTicket
     * @return
     */
    @Override
    public APIResponse editPlaceTicketSale(ReqPlaceTicket reqPlaceTicket) {
        if (reqPlaceTicket == null) {
            return APIResponse.returnFail("reqPlaceTicket为空！");
        }
        TbPlaceTicketSalePlan tbPlaceTicketSalePlan = new TbPlaceTicketSalePlan();
        tbPlaceTicketSalePlan.setId(reqPlaceTicket.getId());
        tbPlaceTicketSalePlan.setPlaceId(reqPlaceTicket.getPlaceId());
        tbPlaceTicketSalePlan.setTicketName(reqPlaceTicket.getTicketName());
        tbPlaceTicketSalePlan.setCategoryId(reqPlaceTicket.getCategoryId());
        tbPlaceTicketSalePlan.setStartWeek(reqPlaceTicket.getStartWeek());
        tbPlaceTicketSalePlan.setEndWeek(reqPlaceTicket.getEndWeek());
        tbPlaceTicketSalePlan.setPrice(reqPlaceTicket.getPrice());
        tbPlaceTicketSalePlan.setMemberPrice(reqPlaceTicket.getMemberPrice());
        tbPlaceTicketSalePlan.setLimitNum(reqPlaceTicket.getLimitNum());
        tbPlaceTicketSalePlan.setDescrible(reqPlaceTicket.getDescrible());
        tbPlaceTicketSalePlan.setCreateUid(reqPlaceTicket.getCreateUid());
        tbPlaceTicketSalePlan.setUpdateUid(reqPlaceTicket.getUpdateUid());
        tbPlaceTicketSalePlan.setIsSaleClient(reqPlaceTicket.getIsSaleClient());

        Date startTime = DateTimeUtils.convertString2Date("HH:mm:ss", reqPlaceTicket.getStartTime());
        Date endTime = DateTimeUtils.convertString2Date("HH:mm:ss", reqPlaceTicket.getEndTime());
        tbPlaceTicketSalePlan.setStartTime(startTime);
        tbPlaceTicketSalePlan.setEndTime(endTime);
        tbPlaceTicketSalePlan.setUpdateTime(new Date());
        //判断门票是否相交
        if (checkTimeAndWeek(reqPlaceTicket.getPlaceId(), reqPlaceTicket.getCategoryId(), startTime, endTime, reqPlaceTicket.getStartWeek(), reqPlaceTicket.getEndWeek(),reqPlaceTicket.getId())) {
            //return APIResponse.returnFail("存在有相交或包含关系的门票！");
            logger.debug("存在有相交或包含关系的门票！");
//            tbPlaceTicketSalePlan.setStartTime(null);
//            tbPlaceTicketSalePlan.setEndTime(null);
//            tbPlaceTicketSalePlan.setStartWeek(null);
//            tbPlaceTicketSalePlan.setEndWeek(null);
            return APIResponse.returnFail("存在有相交或包含关系的门票！");
        }
        int flag = tbPlaceTicketSalePlanMapper.updateByPrimaryKeySelective(tbPlaceTicketSalePlan);
        return APIResponse.returnSuccess(flag==1?true:false);
    }

    /**
     * 门票查询会员卡根据手机号
     * @param placeId
     * @param phone
     * @return
     */
    @Override
    public APIResponse queryNumCardList(Integer placeId, String phone) {
        Integer memberUid = this.getUidByPhone(phone);
        if (StringUtils.isEmpty(memberUid)){
            logger.debug("该电话没有对应的会员！");
            return APIResponse.returnSuccess();
        }
        List<Integer> placeIdList = new ArrayList<Integer>();
        if (placeMemberService.checkIsShareVip(placeId)){
            placeIdList = placeMemberService.getShareVipPlaceIds(placeId);
        }

        //根据会员uid，placeId查询该场馆所有次卡
        TbBizPlaceMemberCardExample example = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria criteria1 = example.createCriteria();
        TbBizPlaceMemberCardExample.Criteria criteria2 = example.createCriteria();
        criteria1.andMemberUidEqualTo(memberUid);
        if (placeIdList.size() > 1){
            criteria1.andPlaceIdIn(placeIdList);
        } else {
            criteria1.andPlaceIdEqualTo(placeId);
        }
        //criteria1.andCardTypeEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER);
        //criteria1.andSurplusNumbersNotEqualTo(0);
        criteria1.andDeadLineTimeGreaterThan(new Date());//判断截止日期 --指定有效期
        criteria1.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria1.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        criteria1.andIsSupportTicketsEqualTo(Constants.YES);

        criteria2.andMemberUidEqualTo(memberUid);
        if (placeIdList.size() > 1){
            criteria2.andPlaceIdIn(placeIdList);
        } else {
            criteria2.andPlaceIdEqualTo(placeId);
        }
        //criteria2.andCardTypeEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER);
        //criteria2.andSurplusNumbersNotEqualTo(0);
        criteria2.andDeadLineTimeIsNull();//判断截止日期 --无限制
        criteria2.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria2.andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        criteria2.andIsSupportTicketsEqualTo(Constants.YES);
        example.or(criteria2);
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(tbBizPlaceMemberCardList)){
            return APIResponse.returnSuccess(null);
        }
        List<RespNumberCard> respNumberCardList = tbBizPlaceMemberCardList2RespNumberCardList(tbBizPlaceMemberCardList);
        if (CollectionUtils.isNotEmpty(respNumberCardList)){
            return APIResponse.returnSuccess(respNumberCardList);
        }
        logger.debug("查不到该用户存在次卡信息！");
        return APIResponse.returnSuccess(null);
    }

    
    /**
     * 门票查询会员卡根据手机号、姓名模糊查询
     * @param placeId
     * @param key
     * @return
     */
    @Override
    public APIResponse querymemberNumCardList(Integer placeId, String key) {
      
        List<Integer> placeIdList = new ArrayList<Integer>();
        if (placeMemberService.checkIsShareVip(placeId)){
            placeIdList = placeMemberService.getShareVipPlaceIds(placeId);
        }
        
        ReqPlaceMemberSearch reqMemberSearch = new ReqPlaceMemberSearch();
        reqMemberSearch.setPlaceId(placeId);
        reqMemberSearch.setKey(key);
        reqMemberSearch.setPlaceIdList(placeIdList);
        
        List<RespMemberCardInfo> memberCardInfoList = vPlaceMemberMapper.queryPlaceMemberNumCardByCondition(reqMemberSearch);
        if (CollectionUtils.isNotEmpty(memberCardInfoList)) {
        	//遍历次卡获取门票销售计划
			for (RespMemberCardInfo respMemberCardInfo : memberCardInfoList) {
				
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(respMemberCardInfo.getCardClassify())){
				    TbBizPlaceMemberCardTypeTicketExample tbBizPlaceMemberCardTypeTicketExample = new TbBizPlaceMemberCardTypeTicketExample();
	                TbBizPlaceMemberCardTypeTicketExample.Criteria tbBizPlaceMemberCardTypeTicketCriteria = tbBizPlaceMemberCardTypeTicketExample.createCriteria();
	                tbBizPlaceMemberCardTypeTicketCriteria.andCardTypeIdEqualTo(respMemberCardInfo.getMemberCardType());
	                
	                List<TbBizPlaceMemberCardTypeTicket> tbBizPlaceMemberCardTypeTicketList = tbBizPlaceMemberCardTypeTicketMapper.selectByExample(tbBizPlaceMemberCardTypeTicketExample);
	                if (!CollectionUtils.isEmpty(tbBizPlaceMemberCardTypeTicketList)){
	               
	                    List<Integer> ticketIds = new ArrayList<Integer>();
	                    for (TbBizPlaceMemberCardTypeTicket tbBizPlaceMemberCardTypeTicket : tbBizPlaceMemberCardTypeTicketList){
	                        ticketIds.add(tbBizPlaceMemberCardTypeTicket.getTicketId());
	                    }
	                    TbPlaceTicketSalePlanExample tbPlaceTicketSalePlanExample = new TbPlaceTicketSalePlanExample();
	                    TbPlaceTicketSalePlanExample.Criteria tbPlaceTicketSalePlanCriteria = tbPlaceTicketSalePlanExample.createCriteria();
	                    tbPlaceTicketSalePlanCriteria.andIdIn(ticketIds);
	                    List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlanList = tbPlaceTicketSalePlanMapper.selectByExample(tbPlaceTicketSalePlanExample);
	                    
	                    respMemberCardInfo.setTicketSalePlanList(tbPlaceTicketSalePlanList);
	                }
				}
			}
		}
        return APIResponse.returnSuccess(memberCardInfoList);
    }

    
    /**
     * 购买门票
     * @param reqTicketPay
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse ticketPay(ReqTicketPay reqTicketPay) throws Exception{

        Integer memberCardId = reqTicketPay.getMemberCardId();
        List<ReqTicketSale> reqTicketSaleList = reqTicketPay.getTicketSaleList();
        String phone = reqTicketPay.getContactInformation();
        String orderId = null;
        Integer uid = null;
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = null;
        if (CollectionUtils.isEmpty(reqTicketSaleList)){
            return APIResponse.returnFail("没有选择门票！");
        }
//        if (!StringUtils.isEmpty(reqTicketPay.getReceivedCount())){
//            if (reqTicketSaleList.get(0).getCount() != reqTicketPay.getReceivedCount()){
//                return APIResponse.returnFail("扣除次数与门票张数不一致！");
//            }
//        }

        TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
        if (!StringUtils.isEmpty(memberCardId)){
            //会员买门票
            tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(memberCardId);
            /*Date currentDate = new Date();
            DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableEndTime());
            currentDate = DateTimeUtils.convertString2Date("HH:mm:ss",DateTimeUtils.convertDate2String("HH:mm:ss",currentDate));
            Date startDate = DateTimeUtils.convertString2Date("HH:mm:ss",DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableStartTime()));
            Date endDate = DateTimeUtils.convertString2Date("HH:mm:ss",DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableEndTime()));
            boolean flag1 = DateUtils.dateCompare(currentDate,startDate,true);//购票时间>=会员卡优惠开始时间返回true
            boolean flag2 = DateUtils.dateCompare(endDate,currentDate,true);//会员卡优惠结束时间>=购票时间true
            if (!(flag1 && flag2)){
                throw new Exception("您选择的会员卡仅支持"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableStartTime())+"-"+DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceMemberCard.getAvailableEndTime())+"时间段的场馆费用支付");
            }*/
            //符合的运动类别
            if (tbBizPlaceMemberCard.getIsSupportTickets().equals(PlaceConstants.NO)){
                return APIResponse.returnFail("该卡不支持门票购买！");
            }
            String categoryIds = tbBizPlaceMemberCard.getCategoryIds();

            List categoryList = JSON.parseArray(categoryIds);
            String categoryStr = "";
            for (int i=0;i<categoryList.size();i++){
                categoryStr = categoryStr+iBaseService.getCommonDataCache("cagetory" + categoryList.get(i));
            }
            for (ReqTicketSale reqTicketSale : reqTicketSaleList){
                if (categoryIds.indexOf(reqTicketSale.getCategoryId().toString()) == -1){//不存在运动类型返回-1
                    return APIResponse.returnFail("您选择的会员卡仅支持 "+JSON.toJSON(categoryStr).toString()+" 在内的项目！");
                }
            }
            //生成门票订单
            if (StringUtils.isEmpty(phone)){
                return APIResponse.returnFail("会员电话不能为空！");
            }
            Integer memberUid = getUidByPhone(phone);
            if (StringUtils.isEmpty(memberUid)){
                return APIResponse.returnFail("不存在该会员！");
            }
            orderId = this.getBizOrderId(memberUid);
            uid = memberUid;
            tbBizPlaceOrderItems  = this.reqTicketSalePlan2OrderItem(reqTicketSaleList,memberUid,orderId,true,tbBizPlaceMemberCard);
        } else {
            //普通
            if (StringUtils.isEmpty(reqTicketPay.getCreateUid())){
                return APIResponse.returnFail("createUid不能为空！");
            }
            if (reqTicketSaleList.size() > 1){
                return APIResponse.returnFail("不支持购买多种门票！");
            }
            orderId = this.getBizOrderId(reqTicketPay.getCreateUid());
            uid = reqTicketPay.getCreateUid();
            tbBizPlaceOrderItems  = this.reqTicketSalePlan2OrderItem(reqTicketSaleList,reqTicketPay.getCreateUid(),orderId,false,null);
        }
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("订单明细为空！");
        }
        BigDecimal price = new BigDecimal(0);
        BigDecimal singlePrice = new BigDecimal(0);
        BigDecimal notMemberPrice = new BigDecimal(0);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsNotMember  = this.reqTicketSalePlan2OrderItem(reqTicketSaleList,reqTicketPay.getCreateUid(),orderId,false,null);
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsNotMember) {
            if (null != item.getTicketCount() && null != item.getSalePrice()){
                notMemberPrice = notMemberPrice.add(item.getSalePrice().multiply(new BigDecimal(item.getTicketCount())));
            }
        }


        Map priceMap = new HashMap();
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            singlePrice = item.getSalePrice();
            if (!priceMap.containsKey(item.getUnitSalePlanId())){
                priceMap.put(item.getUnitSalePlanId(),singlePrice);
            }

            price = price.add(singlePrice.multiply(new BigDecimal(item.getTicketCount())));

            if (!StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                item.setSalePrice(new BigDecimal(reqTicketPay.getReceivedAmount()));
            }else{
                item.setSalePrice(price);
            }

            //插入明细
            tbBizPlaceOrderItemMapper.insert(item);
            logger.debug("===================插入明细数据:TbBizPlaceOrderItem:{}", JSON.toJSONString(item));
        }
        //插入订单
        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
        tbBizPlaceOrder.setPlaceOrderId(orderId);
        tbBizPlaceOrder.setCustomerName(org.apache.commons.lang3.StringUtils.isEmpty(reqTicketPay.getName())?"散客":reqTicketPay.getName());
        tbBizPlaceOrder.setMobile(reqTicketPay.getContactInformation());
        tbBizPlaceOrder.setDescrible(reqTicketPay.getMemo());
        tbBizPlaceOrder.setPlaceId(reqTicketPay.getPlaceId());
        tbBizPlaceOrder.setCreateUid(reqTicketPay.getCreateUid());
        tbBizPlaceOrder.setPaymentTime(new Date());
        tbBizPlaceOrder.setDebit(notMemberPrice);
        tbBizPlaceOrder.setDate(new Date());
        tbBizPlaceOrder.setEndTime(new Date());
        tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_TICKET);
        tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
        tbBizPlaceOrder.setCategoryId(reqTicketPay.getTicketSaleList().get(0).getCategoryId());
        tbBizPlaceOrder.setExpression(reqTicketPay.getExpression());
        tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
        tbBizPlaceOrder.setUid(uid);
        tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
        if (!StringUtils.isEmpty(memberCardId)){
            tbBizPlaceOrder.setIsMember(PlaceConstants.YES);
            tbBizPlaceOrder.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
        } else {
            tbBizPlaceOrder.setIsMember(PlaceConstants.NO);
        }

        //普通支付
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
        tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);

        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqTicketPay.getPlaceId());
        tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

        if (StringUtils.isEmpty(memberCardId)){
            if (!StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(reqTicketPay.getReceivedAmount()).subtract(notMemberPrice));
            }else{
                tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(0));
            }
        }else{
            if (!StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(reqTicketPay.getReceivedAmount()).subtract(price));
            }else{
                tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(0));
            }
        }

        if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) == 0) {
            logger.debug("插入订单失败");
        }
        TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
        tbBizPlacePayItem.setPlaceOrderId(orderId);
        if (!StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
            tbBizPlacePayItem.setAmount(new BigDecimal(reqTicketPay.getReceivedAmount()));
        }else{
            if (!StringUtils.isEmpty(memberCardId)){

                tbBizPlacePayItem.setAmount(price);
            }else{
                tbBizPlacePayItem.setAmount(notMemberPrice);
            }
        }
        tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
        tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqTicketPay.getAdminPayType()).getUnifiedId());
        /*if (!StringUtils.isEmpty(memberCardId)) {
            //支付方式  -- 会员
            tbBizPlacePayItem.setPayType(PlaceConstants.PAY_WAY_FOR_CARD);
        } else {
            //支付方式  -- 现金
            tbBizPlacePayItem.setPayType(reqTicketPay.getAdminPayType());
        }*/
        tbBizPlacePayItem.setPayType(reqTicketPay.getAdminPayType());
        if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) == 0) {
            logger.debug("插入支付明细失败");
        }
        //门票统计
        this.ticketStatistics(reqTicketPay,reqTicketSaleList,priceMap);

        if (!StringUtils.isEmpty(memberCardId)){
            //抵扣会员卡
            substractMemberCard(memberCardId, reqTicketSaleList, reqTicketPay, orderId, uid);
        }

        ReqOrderHistory reqOrderHistory = null;
        //插入支付流水
        if (reqTicketPay.getReceivedAmount() == null){
            if (CollectionUtils.isNotEmpty(reqTicketPay.getTicketSaleList())){
                int count = 0;
                for (ReqTicketSale reqTicketSale : reqTicketPay.getTicketSaleList()){
                    count = count + reqTicketSale.getCount();
                }
                reqOrderHistory = placeOrderUtilService.memberTicket2ReqOrderHistory(tbBizPlaceOrder,count,(byte)0,(byte)0);
            }
        }else{
            reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(tbBizPlaceOrder,new BigDecimal(reqTicketPay.getReceivedAmount()),(byte)0,(byte)0);
        }
        if (reqOrderHistory != null){
            placeOrderUtilService.insertOrderHistory(reqOrderHistory);
        }
        PlacePrintVo placePrintVo = new PlacePrintVo();
        if (!StringUtils.isEmpty(memberCardId)){
            placePrintVo.setIsMember(PlaceConstants.YES);
        }else {
            placePrintVo.setIsMember(PlaceConstants.NO);
        }
        placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_TICKET);
        placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
        return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
    }

    /**
     * 扫码购买门票
     * @param reqTicketPay
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse ticketPayForScanPay(ReqTicketPay reqTicketPay) throws Exception{

        List<ReqTicketSale> reqTicketSaleList = reqTicketPay.getTicketSaleList();
        String phone = reqTicketPay.getContactInformation();
        String orderId = null;
        Integer uid = null;
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = null;
        if (CollectionUtils.isEmpty(reqTicketSaleList)){
            return APIResponse.returnFail("没有选择门票！");
        }

        //普通
        if (StringUtils.isEmpty(reqTicketPay.getCreateUid())){
            return APIResponse.returnFail("createUid不能为空！");
        }
        if (reqTicketSaleList.size() > 1){
            return APIResponse.returnFail("不支持购买多种门票！");
        }
        orderId = this.getBizOrderId(reqTicketPay.getCreateUid());
        uid = reqTicketPay.getCreateUid();
        tbBizPlaceOrderItems  = this.reqTicketSalePlan2OrderItem(reqTicketSaleList,reqTicketPay.getCreateUid(),orderId,false,null);
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("订单明细为空！");
        }
        BigDecimal price = new BigDecimal(0);
        BigDecimal singlePrice = new BigDecimal(0);
        BigDecimal notMemberPrice = new BigDecimal(0);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsNotMember  = this.reqTicketSalePlan2OrderItem(reqTicketSaleList,reqTicketPay.getCreateUid(),orderId,false,null);
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsNotMember) {
            if (null != item.getTicketCount() && null != item.getSalePrice()){
                notMemberPrice = notMemberPrice.add(item.getSalePrice().multiply(new BigDecimal(item.getTicketCount())));
            }
        }
        Map priceMap = new HashMap();
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            singlePrice = item.getSalePrice();
            if (!priceMap.containsKey(item.getUnitSalePlanId())){
                priceMap.put(item.getUnitSalePlanId(),singlePrice);
            }
            price = price.add(singlePrice.multiply(new BigDecimal(item.getTicketCount())));

            if (!StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                item.setSalePrice(new BigDecimal(reqTicketPay.getReceivedAmount()));
            }else{
                item.setSalePrice(price);
            }
            //插入明细
            tbBizPlaceOrderItemMapper.insert(item);
        }
        //插入订单
        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
        tbBizPlaceOrder.setPlaceOrderId(orderId);
        tbBizPlaceOrder.setCustomerName(org.apache.commons.lang3.StringUtils.isEmpty(reqTicketPay.getName())?"散客":reqTicketPay.getName());
        tbBizPlaceOrder.setMobile(phone);
        tbBizPlaceOrder.setDescrible(reqTicketPay.getMemo());
        tbBizPlaceOrder.setPlaceId(reqTicketPay.getPlaceId());
        tbBizPlaceOrder.setCreateUid(reqTicketPay.getCreateUid());
        tbBizPlaceOrder.setPaymentTime(null);
        tbBizPlaceOrder.setExpression(reqTicketPay.getExpression());
        tbBizPlaceOrder.setDebit(notMemberPrice);
        tbBizPlaceOrder.setDate(new Date());
        tbBizPlaceOrder.setEndTime(new Date());
        tbBizPlaceOrder.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
        tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_TICKET);
        tbBizPlaceOrder.setOrderStatusChangeDate(new Date());
        tbBizPlaceOrder.setCategoryId(reqTicketPay.getTicketSaleList().get(0).getCategoryId());
        tbBizPlaceOrder.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        tbBizPlaceOrder.setIsEffective(PlaceConstants.IS_EFFECTIVE_YES);
        tbBizPlaceOrder.setUid(uid);
        tbBizPlaceOrder.setOrderChannel(PlaceConstants.PLACE_ADMIN_PAY_TYPE.byteValue());
        tbBizPlaceOrder.setIsMember(PlaceConstants.NO);

        //扫码支付
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.NOT_PAY_STATUS);
        tbBizPlaceOrder.setPayStatus(PlaceConstants.ORDER_PREPAY_STATUS);

        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqTicketPay.getPlaceId());
        tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());

        if (!StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
            tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(reqTicketPay.getReceivedAmount()).subtract(notMemberPrice));
        }else{
            tbBizPlaceOrder.setHandAdjustAmount(new BigDecimal(0));
        }

        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqTicketPay.getAdminPayType().toString())){
            tbBizPlaceOrder.setIsType(PlaceConstants.YES);
        }
        if (this.tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder) == 0) {
            logger.debug("插入订单失败");
        }
        
        if (!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(reqTicketPay.getAdminPayType().toString())){//非pos生成支付明细
        	TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
            tbBizPlacePayItem.setPlaceOrderId(orderId);
            if (!StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                tbBizPlacePayItem.setAmount(new BigDecimal(reqTicketPay.getReceivedAmount()));
            }else{
                tbBizPlacePayItem.setAmount(notMemberPrice);
            }
            tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
            tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(reqTicketPay.getAdminPayType()).getUnifiedId());

            tbBizPlacePayItem.setPayType(reqTicketPay.getAdminPayType());

            if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) == 0) {
                logger.debug("插入支付明细失败");
            }
		}
        

        return APIResponse.returnSuccess(tbBizPlaceOrder);
    }

    //门票统计(扫码支付)
    public void ticketStatisticsForScanPay(Integer placeId,List<TbBizPlaceOrderItem> tbBizPlaceOrderItems){
        BigDecimal singlePrice = new BigDecimal(0);

        Map priceMap = new HashMap();
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
            singlePrice = item.getSalePrice();
            if (!priceMap.containsKey(item.getUnitSalePlanId())) {
                priceMap.put(item.getUnitSalePlanId(), singlePrice);
            }
        }
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
            TbPlaceTicketStatistics tbPlaceTicketStatistics1 = new TbPlaceTicketStatistics();
            tbPlaceTicketStatistics1.setUpdateTime(new Date());
            tbPlaceTicketStatistics1.setTicketId(tbBizPlaceOrderItem.getUnitSalePlanId());
            tbPlaceTicketStatistics1.setPlaceId(placeId);
            tbPlaceTicketStatistics1.setTotal(tbBizPlaceOrderItem.getTicketCount());
            tbPlaceTicketStatistics1.setSalePrice((BigDecimal) priceMap.get(tbBizPlaceOrderItem.getUnitSalePlanId()));
            tbPlaceTicketStatistics1.setCreateTime(new Date());
            tbPlaceTicketStatistics1.setSaleDate(new Date());
            try{
                int flag = tbPlaceTicketStatisticsMapper.insert(tbPlaceTicketStatistics1);
                if (flag == 1){
                    logger.debug("========================新增门票统计成功。");
                }
            }catch (Exception e){
                //更新门票数
                TbPlaceTicketStatisticsExample tbPlaceTicketStatisticsExample = new TbPlaceTicketStatisticsExample();
                TbPlaceTicketStatisticsExample.Criteria tbPlaceTicketStatisticsCriteria = tbPlaceTicketStatisticsExample.createCriteria();
                tbPlaceTicketStatisticsCriteria.andTicketIdEqualTo(tbBizPlaceOrderItem.getUnitSalePlanId());
                tbPlaceTicketStatisticsCriteria.andSaleDateEqualTo(new Date());
                tbPlaceTicketStatisticsCriteria.andSalePriceEqualTo((BigDecimal) priceMap.get(tbBizPlaceOrderItem.getUnitSalePlanId()));
                List<TbPlaceTicketStatistics> tbPlaceTicketStatisticses2 = tbPlaceTicketStatisticsMapper
                        .selectByExample(tbPlaceTicketStatisticsExample);
                if (CollectionUtils.isNotEmpty(tbPlaceTicketStatisticses2)){//存在，更新
                    TbPlaceTicketStatistics tbPlaceTicketStatistics3 = new TbPlaceTicketStatistics();
                    tbPlaceTicketStatistics3.setId(tbPlaceTicketStatisticses2.get(0).getId());
                    tbPlaceTicketStatistics3.setUpdateTime(new Date());
                    tbPlaceTicketStatistics3.setTotal(tbPlaceTicketStatisticses2.get(0).getTotal()+tbBizPlaceOrderItem.getTicketCount());//门票+
                    tbPlaceTicketStatistics3.setSalePrice((BigDecimal) priceMap.get(tbBizPlaceOrderItem.getUnitSalePlanId()));
                    int flag = tbPlaceTicketStatisticsMapper.updateByPrimaryKeySelective(tbPlaceTicketStatistics3);
                    if (flag == 1){
                        logger.debug("========================更新门票统计成功。");
                    }
                }
            }
        }
        logger.debug("========================门票统计结束。");
    }

    //门票统计
    private void ticketStatistics(ReqTicketPay reqTicketPay,List<ReqTicketSale> reqTicketSaleList,Map priceMap){
        for (ReqTicketSale reqTicketSale : reqTicketSaleList){
            TbPlaceTicketStatistics tbPlaceTicketStatistics1 = new TbPlaceTicketStatistics();
            tbPlaceTicketStatistics1.setUpdateTime(new Date());
            tbPlaceTicketStatistics1.setTicketId(reqTicketSale.getTicketId());
            tbPlaceTicketStatistics1.setPlaceId(reqTicketPay.getPlaceId());
            tbPlaceTicketStatistics1.setTotal(reqTicketSale.getCount());
            tbPlaceTicketStatistics1.setSalePrice((BigDecimal) priceMap.get(reqTicketSale.getTicketId()));
            tbPlaceTicketStatistics1.setCreateTime(new Date());
            tbPlaceTicketStatistics1.setSaleDate(new Date());
            try{
                int flag = tbPlaceTicketStatisticsMapper.insert(tbPlaceTicketStatistics1);
                if (flag == 1){
                    logger.debug("========================新增门票统计成功。");
                }
            }catch (Exception e){
                //更新门票数
                TbPlaceTicketStatisticsExample tbPlaceTicketStatisticsExample = new TbPlaceTicketStatisticsExample();
                TbPlaceTicketStatisticsExample.Criteria tbPlaceTicketStatisticsCriteria = tbPlaceTicketStatisticsExample.createCriteria();
                tbPlaceTicketStatisticsCriteria.andTicketIdEqualTo(reqTicketSale.getTicketId());
                tbPlaceTicketStatisticsCriteria.andSaleDateEqualTo(new Date());
                tbPlaceTicketStatisticsCriteria.andSalePriceEqualTo((BigDecimal) priceMap.get(reqTicketSale.getTicketId()));
                tbPlaceTicketStatisticsExample.setOrderByClause(" id for update ");
                List<TbPlaceTicketStatistics> tbPlaceTicketStatisticses2 = tbPlaceTicketStatisticsMapper
                        .selectByExample(tbPlaceTicketStatisticsExample);
                if (CollectionUtils.isNotEmpty(tbPlaceTicketStatisticses2)){//存在，更新
                    TbPlaceTicketStatistics tbPlaceTicketStatistics3 = new TbPlaceTicketStatistics();
                    tbPlaceTicketStatistics3.setId(tbPlaceTicketStatisticses2.get(0).getId());
                    tbPlaceTicketStatistics3.setUpdateTime(new Date());
                    tbPlaceTicketStatistics3.setTotal(tbPlaceTicketStatisticses2.get(0).getTotal()+reqTicketSale.getCount());//门票+
                    tbPlaceTicketStatistics3.setSalePrice((BigDecimal) priceMap.get(reqTicketSale.getTicketId()));
                    int flag = tbPlaceTicketStatisticsMapper.updateByPrimaryKeySelective(tbPlaceTicketStatistics3);
                    if (flag == 1){
                        logger.debug("========================更新门票统计成功。");
                    }
                }
            }
        }
        logger.debug("========================门票统计结束。");
    }

    /**
     * 修改门票统计 (退款)
     *
     */
    public void updateTicketStatistics(TbBizPlaceOrder tbBizPlaceOrder,List<TbBizPlaceOrderItem> tbBizPlaceOrderItems) throws Exception{
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
            TbPlaceTicketStatisticsExample tbPlaceTicketStatisticsExample = new TbPlaceTicketStatisticsExample();
            TbPlaceTicketStatisticsExample.Criteria tbPlaceTicketStatisticsCriteria = tbPlaceTicketStatisticsExample.createCriteria();
            tbPlaceTicketStatisticsCriteria.andTicketIdEqualTo(tbBizPlaceOrderItem.getUnitSalePlanId());
            tbPlaceTicketStatisticsCriteria.andPlaceIdEqualTo(tbBizPlaceOrder.getPlaceId());

            if (StringUtils.isEmpty(tbBizPlaceOrderItem.getTicketCount()) || tbBizPlaceOrderItem.getTicketCount().intValue() == 0){
                tbPlaceTicketStatisticsCriteria.andSalePriceEqualTo(tbBizPlaceOrderItem.getSalePrice());
            }

            tbPlaceTicketStatisticsCriteria.andSaleDateEqualTo(tbBizPlaceOrderItem.getConsumeTime());
            tbPlaceTicketStatisticsExample.setOrderByClause(" id for update ");
            List<TbPlaceTicketStatistics> tbPlaceTicketStatisticsList = tbPlaceTicketStatisticsMapper.selectByExample(tbPlaceTicketStatisticsExample);
            if (CollectionUtils.isEmpty(tbPlaceTicketStatisticsList)){
                throw new Exception("门票统计失败");
            }
            TbPlaceTicketStatistics  tbPlaceTicketStatistics = tbPlaceTicketStatisticsList.get(0);
            tbPlaceTicketStatistics.setTotal(tbPlaceTicketStatistics.getTotal()-tbBizPlaceOrderItem.getTicketCount());
            int flag1 = tbPlaceTicketStatisticsMapper.updateByPrimaryKeySelective(tbPlaceTicketStatistics);
            if (flag1 != 1){
                throw new Exception("门票统计更新异常");
            }
        }
    }


    /**
     * 修改门票统计 (明细部分退款)
     *
     */
    @Override
	public void updateTicketStatisticsByPart(TbBizPlaceOrder tbBizPlaceOrder,
			TbBizPlaceOrderItem tbBizPlaceOrderItem, Integer refundTicketCount) throws Exception {

        TbPlaceTicketStatisticsExample tbPlaceTicketStatisticsExample = new TbPlaceTicketStatisticsExample();
        TbPlaceTicketStatisticsExample.Criteria tbPlaceTicketStatisticsCriteria = tbPlaceTicketStatisticsExample.createCriteria();
        tbPlaceTicketStatisticsCriteria.andTicketIdEqualTo(tbBizPlaceOrderItem.getUnitSalePlanId());
        tbPlaceTicketStatisticsCriteria.andPlaceIdEqualTo(tbBizPlaceOrder.getPlaceId());

      /*  if (StringUtils.isEmpty(tbBizPlaceOrderItem.getTicketCount()) || tbBizPlaceOrderItem.getTicketCount().intValue() == 0){
            tbPlaceTicketStatisticsCriteria.andSalePriceEqualTo(tbBizPlaceOrderItem.getSalePrice());
        }*/

        tbPlaceTicketStatisticsCriteria.andSaleDateEqualTo(tbBizPlaceOrderItem.getConsumeTime());
        tbPlaceTicketStatisticsExample.setOrderByClause(" id for update ");
        List<TbPlaceTicketStatistics> tbPlaceTicketStatisticsList = tbPlaceTicketStatisticsMapper.selectByExample(tbPlaceTicketStatisticsExample);
        if (CollectionUtils.isEmpty(tbPlaceTicketStatisticsList)){
            throw new Exception("门票统计失败");
        }
        TbPlaceTicketStatistics  tbPlaceTicketStatistics = tbPlaceTicketStatisticsList.get(0);
        int total=tbPlaceTicketStatistics.getTotal()-refundTicketCount;//该笔明细退的门票
        tbPlaceTicketStatistics.setTotal(total);
        int flag1 = tbPlaceTicketStatisticsMapper.updateByPrimaryKeySelective(tbPlaceTicketStatistics);
        if (flag1 != 1){
            throw new Exception("门票统计更新异常");
        }
    
    
		
	}
    
    /**
     * 抵扣会员卡
     * @param memberCardId
     * @param reqTicketSaleList
     * @param reqTicketPay
     * @param orderId
     * @param uid
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private APIResponse<?> substractMemberCard(Integer memberCardId,
                                     List<ReqTicketSale> reqTicketSaleList,
                                     ReqTicketPay reqTicketPay,
                                     String orderId,
                                     Integer uid) throws Exception{
        BigDecimal receivedAmount = new BigDecimal(0);
        //会员扣除次卡次数
        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardById(memberCardId);
        int count = 0;
        for (ReqTicketSale reqTicketSale : reqTicketSaleList){
            count = count + reqTicketSale.getCount();
        }
        BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
        BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
        BigDecimal zeroAmount = new BigDecimal(0);
        Integer initNumber = tbBizPlaceMemberCard.getSurplusNumbers();
        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())){
            //次卡情况
//                if (StringUtils.isEmpty(reqTicketPay.getReceivedCount())){
//                    return APIResponse.returnFail("实扣次数不能为空！");
//                }
            //验证门票和会员卡是否被绑定
            List<Integer> notBindTicketIds = new ArrayList<>();
            for (ReqTicketSale reqTicketSale : reqTicketSaleList) {
                TbBizPlaceMemberCardTypeTicket typeTicket = tbBizPlaceMemberCardTypeTicket(tbBizPlaceMemberCard.getCardTypeId(),reqTicketSale.getTicketId());
                if (StringUtils.isEmpty(typeTicket)){
                    notBindTicketIds.add(reqTicketSale.getTicketId());
                }
            }
            if (CollectionUtils.isNotEmpty(notBindTicketIds)){
                TbPlaceTicketSalePlanExample example = new TbPlaceTicketSalePlanExample();
                TbPlaceTicketSalePlanExample.Criteria criteria = example.createCriteria();
                criteria.andIdIn(notBindTicketIds);
                List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlanList = tbPlaceTicketSalePlanMapper.selectByExample(example);
                List<String> notBindTicketNameList = new ArrayList<>();
                for (TbPlaceTicketSalePlan tbPlaceTicketSalePlan : tbPlaceTicketSalePlanList){
                    notBindTicketNameList.add(tbPlaceTicketSalePlan.getTicketName());
                }
                if (CollectionUtils.isNotEmpty(notBindTicketNameList)){
                    return APIResponse.returnFail("该次卡不支持以下门票：" + notBindTicketNameList.toString());
                }
            }
            if (tbBizPlaceMemberCard.getSurplusNumbers()>=count/*reqTicketPay.getReceivedCount()*/){
                tbBizPlaceMemberCard.setSurplusNumbers(tbBizPlaceMemberCard.getSurplusNumbers()-count
                            /*tbBizPlaceMemberCard.getSurplusNumbers()-reqTicketPay.getReceivedCount()*/);
            } else {
                throw new Exception("次卡剩余次数不够本次抵扣！");
            }
        }
        else if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE.equals(tbBizPlaceMemberCard.getCardType())){
            //储值卡
            if (StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                return APIResponse.returnFail("实收金额不能为空！");
            }
            receivedAmount = new BigDecimal(reqTicketPay.getReceivedAmount());
            //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
            if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(receivedAmount)){
                //会员卡上的本金大于等于消费金额
                if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
                    tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
                }
                else{
                    //会员卡上的本金+赠送金额大于等于消费金额
                    if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
                        BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
                        tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
                        tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
                    }else{
                        throw new Exception("请充值会员卡！");
                    }
                }
            }
        }
        else if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
            //折扣卡
            if (StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                return APIResponse.returnFail("实收金额不能为空！");
            }
            receivedAmount = new BigDecimal(reqTicketPay.getReceivedAmount());
            //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
            if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(receivedAmount)){
                //会员卡上的本金大于等于消费金额
                if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
                    tbBizPlaceMemberCard.setSurplusAmount(initAmount.subtract(receivedAmount));
                }
                else{
                    throw new Exception("请充值会员卡！");
                }
            }
        }
        else if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
            //储值折扣卡
            if (StringUtils.isEmpty(reqTicketPay.getReceivedAmount())){
                return APIResponse.returnFail("实收金额不能为空！");
            }
            receivedAmount = new BigDecimal(reqTicketPay.getReceivedAmount());
            //扣除该会员卡余额  先扣除本金，本金不够再扣除赠送余额，赠送余额不够支付订场失败
            if (!StringUtils.isEmpty(initAmount) && !StringUtils.isEmpty(receivedAmount)){
                //会员卡上的本金大于等于消费金额
                if (initAmount.doubleValue() >= receivedAmount.doubleValue()){
                    tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(receivedAmount));
                }
                else{
                    //会员卡上的本金+赠送金额大于等于消费金额
                    if (initAmount.add(initGiveAmount).doubleValue() >= receivedAmount.doubleValue()){
                        BigDecimal surplusGiveAmount = initGiveAmount.subtract(receivedAmount.subtract(initAmount));
                        tbBizPlaceMemberCard.setSurplusAmount(zeroAmount);
                        tbBizPlaceMemberCard.setSurplusGiveAmount(surplusGiveAmount);
                    }else{
                        throw new Exception("请充值会员卡！");
                    }
                }
            }
        }
        int flag = tbBizPlaceMemberCardMapper.updateByPrimaryKeySelective(tbBizPlaceMemberCard);
        if (flag == 1){
            logger.debug("========================次卡抵扣成功。");
            TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
            tbBizPlaceMemberOpHistory.setCreateUid(reqTicketPay.getCreateUid());
            tbBizPlaceMemberOpHistory.setPlaceId(reqTicketPay.getPlaceId());
            tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
            if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())){
                //次卡情况
                tbBizPlaceMemberOpHistory.setAmount(new BigDecimal(0));
                tbBizPlaceMemberOpHistory.setOpBeforeNumbers(/*tbBizPlaceMemberCard.getSurplusNumbers()+count*/
                        initNumber);
            }else{
                tbBizPlaceMemberOpHistory.setAmount(receivedAmount);//抵扣价格
                tbBizPlaceMemberOpHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
            }
            tbBizPlaceMemberOpHistory.setCreateTime(new Date());
            tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
            //TODO 生成流水号
            tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqTicketPay.getPlaceId()));
            tbBizPlaceMemberOpHistory.setOrderNo(orderId);
            tbBizPlaceMemberOpHistory.setOpTypeName("商家端-"
                    +iBaseService.getCommonDataCache("cagetory" + reqTicketSaleList.get(0).getCategoryId())+"门票抵扣");
            if (!StringUtils.isEmpty(reqTicketPay.getContactInformation()) && !StringUtils.isEmpty(reqTicketPay.getName())){
                tbBizPlaceMemberOpHistory.setUid(uid);
            }
            tbBizPlaceMemberOpHistory.setUserName(reqTicketPay.getName());
            tbBizPlaceMemberOpHistory.setMobile(reqTicketPay.getContactInformation());
            TbBizPlaceMemberCard tbBizPlaceMemberCard1 = tbBizPlaceMemberCardMapper
                    .selectByPrimaryKey(reqTicketPay.getMemberCardId());
            tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
            tbBizPlaceMemberOpHistory.setMemo(reqTicketPay.getMemo());
            tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
            tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
            tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
            tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
            tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
            tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
            tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
            tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());
            tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
            tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
            tbBizPlaceMemberOpHistory.setOpCardCount(count/*reqTicketPay.getReceivedCount()*/);
            tbBizPlaceMemberOpHistory.setPayType(reqTicketPay.getAdminPayType());
            tbBizPlaceMemberOpHistory.setAdminPayType(PayTypeEnum.getEnum(reqTicketPay.getAdminPayType()).getUnifiedId());
            tbBizPlaceMemberOpHistory.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());//后台买门票
            int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
            if (flag2 !=1 ) {
                throw new Exception("次卡明细记录异常");
            }

            TbBizPlace place=placeBaseService.getPlaceById(reqTicketPay.getPlaceId());
            List<String> mobileList=new ArrayList<>();
            List<String> paramList=new ArrayList<>();
            //成功购买门票发送短信提醒
            String[] args = new String[7];
            args[0] = place != null ? place.getName() : "";
            args[1] = tbBizPlaceMemberCard != null ? tbBizPlaceMemberCard.getCardName() : "";
            args[2] = DateUtils.getCurrentTime();
            args[3] ="购买门票";
            if (tbBizPlaceMemberCard.getCardType()==4){
                args[4] = count+"次";
                args[5] =tbBizPlaceMemberCard.getSurplusNumbers().toString()+"次";
            }else{
                args[4] = receivedAmount != null ? receivedAmount.toString()+"元": "";
                args[5]=tbBizPlaceMemberCard!=null?tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).toString()+"元":"";
            }

            // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(reqTicketPay.getPlaceId());
            if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
                args[6]=placeAttach.getBookingConsultPhone();
            } else {
                // 获取系统配置的百灵鸟客服热线
                TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                args[6]=parameterVo!=null?parameterVo.getParameterValue():"";
            }
            mobileList.add(reqTicketPay.getContactInformation());
            paramList.addAll(Arrays.asList(args));
            try{
                //this.asyncSendSms(reqTicketPay.getContactInformation(), SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, args, true);
                placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
            }catch(java.lang.Exception e){
                logger.info("短信发送失败-------->"+e.getMessage());
            }
            logger.debug("-------------------次卡明细记录完毕-------------");
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 门票销售明细报表
     * @param placeId
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public APIResponse ticketSaleDetail(Integer placeId, Date startDate, Date endDate,Integer pageNum,Integer pageSize) {
        int totalNum = tbPlaceTicketStatisticsPlusMapper.countTicketStatistics(placeId,startDate,endDate);
        List<RespPlaceTicketStatistics> respPlaceTicketStatisticseList = tbPlaceTicketStatisticsPlusMapper.selectTicketStatisticsList(placeId,startDate,endDate,pageNum*pageSize,pageSize);
        if (CollectionUtils.isEmpty(respPlaceTicketStatisticseList)){
            return APIResponse.returnSuccess();
        }
        for (RespPlaceTicketStatistics respPlaceTicketStatistics : respPlaceTicketStatisticseList){
            respPlaceTicketStatistics.setCategoryName(iBaseService.getCommonDataCache("cagetory" + respPlaceTicketStatistics.getTicket().getCategoryId()));
        }
        PageObj<List<RespPlaceTicketStatistics>> result = PageObj.create(totalNum, pageNum, pageSize, respPlaceTicketStatisticseList);
        return APIResponse.returnSuccess(result);
    }

    /**
     * 门票销售明细报表导出
     * @param placeId
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public APIResponse ticketSaleDetailExport(Integer placeId, Date startDate, Date endDate) {
        List<RespPlaceTicketStatistics> respPlaceTicketStatisticseList = tbPlaceTicketStatisticsPlusMapper
                .selectTicketStatisticsListExport(placeId,startDate,endDate);
        if (CollectionUtils.isEmpty(respPlaceTicketStatisticseList)){
            return APIResponse.returnSuccess();
        }
        for (RespPlaceTicketStatistics respPlaceTicketStatistics : respPlaceTicketStatisticseList){
            respPlaceTicketStatistics.setCategoryName(iBaseService.getCommonDataCache("cagetory"
                    + respPlaceTicketStatistics.getTicket().getCategoryId()));
        }
        PageObj<List<RespPlaceTicketStatistics>> result = PageObj.create(0, 0, 0, respPlaceTicketStatisticseList);
        return APIResponse.returnSuccess(result);
    }

    public List<TbBizPlaceOrderItem> reqTicketSalePlan2OrderItem(List<ReqTicketSale> reqTicketSaleList,
                                                                 Integer uid,
                                                                 String orderId,
                                                                 boolean isMember,
                                                                 TbBizPlaceMemberCard tbBizPlaceMemberCard){
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = new ArrayList<>();
        for (ReqTicketSale reqTicketSale : reqTicketSaleList){
            TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
            tbBizPlaceOrderItem.setPlaceOrderId(orderId);
            tbBizPlaceOrderItem.setUnitSalePlanId(reqTicketSale.getTicketId());
            TbPlaceTicketSalePlan tbPlaceTicketSalePlan = tbPlaceTicketSalePlanMapper
                    .selectByPrimaryKey(reqTicketSale.getTicketId());
            if(isMember){//会员价 -- 总票数价格
                /*if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())
                        || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
                    //折扣卡或储值折扣情况
                    BigDecimal discount = new BigDecimal(tbBizPlaceMemberCard.getDiscount()).divide(new BigDecimal(100));
                    tbBizPlaceOrderItem.setSalePrice(tbPlaceTicketSalePlan.getMemberPrice().multiply(discount));
                }else{
                    tbBizPlaceOrderItem.setSalePrice(tbPlaceTicketSalePlan.getMemberPrice());
                }*/
            	/* */
            	
                /*************add start***/
            	Map<String,Object> params=new HashMap<>();
            	params.put("memberCardId", tbBizPlaceMemberCard.getId());
                List<TbBizPlaceMemberCardTypeInitAmount> memberCardTypeList = posUnionPayMapper
                        .selectCardTypeInitAmoutByPK(params);
                TbBizPlaceMemberCardTypeInitAmount memberCardType = null;
                if (null != memberCardTypeList && memberCardTypeList.size() > 0){
                    memberCardType = memberCardTypeList.get(0);
                }
                if (memberCardType != null) {
                	 int cardTypeTmp=memberCardType.getCardType();
                     if(cardTypeTmp==4){//卡类型(1:储值卡 2：折扣卡 3：储值折扣卡 4：次卡)，有以上几种，其中次卡比较特殊主要针对门票
                     	BigDecimal cardpric=(memberCardType.getInitAmount().divide(new BigDecimal(memberCardType.getFrequency()),2,BigDecimal.ROUND_HALF_UP));//计算次卡单价

                         tbBizPlaceOrderItem.setSalePrice(cardpric);
                     }else{
                    	 tbBizPlaceOrderItem.setSalePrice(tbPlaceTicketSalePlan.getMemberPrice());
                     }
                }

                /*************add end 次卡价格实收金额修正 by tim 2017/3/14**/

            }else{//普通用户 -- 总票数价格
                tbBizPlaceOrderItem.setSalePrice(tbPlaceTicketSalePlan.getPrice());
            }
            tbBizPlaceOrderItem.setVersion(0);
            tbBizPlaceOrderItem.setTicketCount(reqTicketSale.getCount());
            tbBizPlaceOrderItem.setCreateUid(uid);
            tbBizPlaceOrderItem.setConsumeTime(new Date());
            tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
            tbBizPlaceOrderItem.setUseType(PlaceConstants.ORDER_USE_TICKET);
            tbBizPlaceOrderItem.setGoodsId(tbPlaceTicketSalePlan.getId());
            tbBizPlaceOrderItem.setGoodsName(tbPlaceTicketSalePlan.getTicketName());
            tbBizPlaceOrderItem.setSurplusGoodsCount(reqTicketSale.getCount());
            tbBizPlaceOrderItem.setTotalGoodsCount(reqTicketSale.getCount());
            tbBizPlaceOrderItem.setStartTime(tbPlaceTicketSalePlan.getStartTime());
            tbBizPlaceOrderItem.setEndTime(tbPlaceTicketSalePlan.getEndTime());
            tbBizPlaceOrderItem.setOriginPrice(tbPlaceTicketSalePlan.getPrice());
            tbBizPlaceOrderItem.setMemberPrice(tbPlaceTicketSalePlan.getMemberPrice());
            tbBizPlaceOrderItemList.add(tbBizPlaceOrderItem);
        }
        return  tbBizPlaceOrderItemList;
    }

    /**
     * 门票生成订单号
     * @param uid
     * @return
     */
    public String getBizOrderId(Integer uid) {
        return CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, uid);
    }

    /**
     * 根据电话查询会员uid
     * @param phone
     * @return
     */
    public Integer getUidByPhone(String phone) {
        TbBizPlaceMemberExample example = new TbBizPlaceMemberExample();
        TbBizPlaceMemberExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andMobileEqualTo(phone.trim());
        example.setDistinct(true);
        List<TbBizPlaceMember> tbBizPlaceMemberList = tbBizPlaceMemberMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberList)){
            return tbBizPlaceMemberList.get(0).getUid();
        }
        return null;
    }


    /**
     * 生成门票saleNo
     *
     * @return
     */
    private String createSaleNo() {
        UUID randomUUID = UUID.randomUUID();
        String uuid = randomUUID.toString().replaceAll("-", "");
        StringBuffer bf = new StringBuffer();
        bf.append(uuid);
        return bf.toString().toLowerCase();
    }

    /**
     * 判断门票是否相交
     * 相交返回true 不相交返回false
     * @param placeId
     * @param categoryId
     * @param startTime
     * @param endTime
     * @param startWeek
     * @param endWeek
     * @return
     */
    private boolean checkTimeAndWeek(Integer placeId, Integer categoryId, Date startTime, Date endTime, Byte startWeek, Byte endWeek,Integer ticketId) {
        TbPlaceTicketSalePlanExample example = new TbPlaceTicketSalePlanExample();
        TbPlaceTicketSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andCategoryIdEqualTo(categoryId);
        criteria.andIsEffectiveEqualTo(PlaceConstants.IS_EFFECTIVE_YES);
        criteria.andStatusEqualTo(PlaceConstants.PLACE_TICKET_STATUS_ENABLE);

        if (!StringUtils.isEmpty(ticketId)){
            criteria.andIdNotEqualTo(ticketId);
        }
        List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlanList = tbPlaceTicketSalePlanMapper.selectByExample(example);
        Rectangle ra = new Rectangle((int)startTime.getTime(), startWeek, (int)endTime.getTime()-(int)startTime.getTime(), (endWeek-startWeek)+1);
        for (TbPlaceTicketSalePlan tbPlaceTicketSalePlan : tbPlaceTicketSalePlanList) {
//            tbPlaceTicketSalePlan.getStartTime();
//            tbPlaceTicketSalePlan.getEndTime();
//            tbPlaceTicketSalePlan.getStartWeek();
//            tbPlaceTicketSalePlan.getEndWeek();

            //如果指定的 Rectangle 与此 Rectangle 相交，则返回 true；否则返回 false。
            int endweek = tbPlaceTicketSalePlan.getEndWeek();
            int startweek = tbPlaceTicketSalePlan.getStartWeek();

            Rectangle rb = new Rectangle((int)tbPlaceTicketSalePlan.getStartTime().getTime(), startweek, (int)tbPlaceTicketSalePlan.getEndTime().getTime()-(int)tbPlaceTicketSalePlan.getStartTime().getTime(), (endweek-startweek)+1);
            if (ra.intersects(rb)){
                logger.debug("两矩形门票相交！");
                return true;
            }
        }
        return false;
    }

    private TbBizPlaceMemberCardTypeTicket tbBizPlaceMemberCardTypeTicket(Integer cardTypeId,Integer ticketId){
        TbBizPlaceMemberCardTypeTicketExample typeTicketExample = new TbBizPlaceMemberCardTypeTicketExample();
        TbBizPlaceMemberCardTypeTicketExample.Criteria criteria = typeTicketExample.createCriteria();
        if (cardTypeId != null){
            criteria.andCardTypeIdEqualTo(cardTypeId);
        }
        if (ticketId != null){
            criteria.andTicketIdEqualTo(ticketId);
        }
        List<TbBizPlaceMemberCardTypeTicket> list = tbBizPlaceMemberCardTypeTicketMapper.selectByExample(typeTicketExample);
        if (list != null && list.size()>0){
            return list.get(0);
        }
        return null;
    }

    @Override
    @Async
    public void asyncSendSms(String phone, Byte templateId, String[] args, boolean failResend){
       // smsService.sendMessageToPhone(phone, templateId, args, failResend);
    }

    /**
     * 同一手机短信连续发送短信一秒钟不能超过一条
     * @param phone
     * @param phoneCompare
     * @param templateId
     * @param args
     * @param failResend
     */
    @Async
    public void asyncSendSmsToOperator(String phone,String phoneCompare, Byte templateId, String[] args, boolean failResend){
    //解决同一手机号发送短信一秒钟不能超过1条
        if (phone.equals(phoneCompare)){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        smsService.sendMessageToPhone(phone, templateId, args, failResend);
    }

    private List<RespNumberCard> tbBizPlaceMemberCardList2RespNumberCardList(List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList){
        List<RespNumberCard> respNumberCards = new ArrayList<RespNumberCard>();
        for (TbBizPlaceMemberCard tbBizPlaceMemberCard : tbBizPlaceMemberCardList){
            RespNumberCard respNumberCard = new RespNumberCard();
            BeanUtils.copyProperties(tbBizPlaceMemberCard,respNumberCard);
            TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper
                    .selectByPrimaryKey(tbBizPlaceMemberCard.getCardTypeId());
            respNumberCard.setInitAmount(tbBizPlaceMemberCardType.getInitAmount());
            respNumberCard.setFrequency(tbBizPlaceMemberCardType.getFrequency());
            
            if (tbBizPlaceMemberCard.getCardType().equals(PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER)){
                TbBizPlaceMemberCardTypeTicketExample tbBizPlaceMemberCardTypeTicketExample = new TbBizPlaceMemberCardTypeTicketExample();
                TbBizPlaceMemberCardTypeTicketExample.Criteria tbBizPlaceMemberCardTypeTicketCriteria = tbBizPlaceMemberCardTypeTicketExample.createCriteria();

                tbBizPlaceMemberCardTypeTicketCriteria.andCardTypeIdEqualTo(tbBizPlaceMemberCard.getCardTypeId());
                List<TbBizPlaceMemberCardTypeTicket> tbBizPlaceMemberCardTypeTicketList = tbBizPlaceMemberCardTypeTicketMapper.selectByExample(tbBizPlaceMemberCardTypeTicketExample);
                if (CollectionUtils.isEmpty(tbBizPlaceMemberCardTypeTicketList)){
                    respNumberCard.setTicketList(null);
                }else{
                    List<Integer> ticketIds = new ArrayList<Integer>();
                    for (TbBizPlaceMemberCardTypeTicket tbBizPlaceMemberCardTypeTicket : tbBizPlaceMemberCardTypeTicketList){
                        ticketIds.add(tbBizPlaceMemberCardTypeTicket.getTicketId());//无须判空
                    }
                    TbPlaceTicketSalePlanExample tbPlaceTicketSalePlanExample = new TbPlaceTicketSalePlanExample();
                    TbPlaceTicketSalePlanExample.Criteria tbPlaceTicketSalePlanCriteria = tbPlaceTicketSalePlanExample.createCriteria();
                    tbPlaceTicketSalePlanCriteria.andIdIn(ticketIds);
                    List<TbPlaceTicketSalePlan> tbPlaceTicketSalePlanList = tbPlaceTicketSalePlanMapper.selectByExample(tbPlaceTicketSalePlanExample);
                    respNumberCard.setTicketList(tbPlaceTicketSalePlanList);
                }
            }
            respNumberCards.add(respNumberCard);
        }
        return respNumberCards;
    }

    @Override
    public Integer getTicketSaleCountByOrderNo(String orderNo) {
        TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
        TbBizPlaceOrderItemExample.Criteria itemExampleCriteria = itemExample.createCriteria();
        itemExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        List<TbBizPlaceOrderItem> items = tbBizPlaceOrderItemMapper.selectByExample(itemExample);
        if(null != items && items.size() != 0){
           return items.get(0).getTicketCount();
        }
        return 0;
    }

    /**
     * 门票销售明细
     *
     * @param map
     * @return
     */
    public APIResponse<PageObj<RespPlaceTicketDetailSum>> getTicketDetail(@Param("map") Map<String, Object> map){
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer reqPageNum = MapUtils.getInteger(map, "pageNum");
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageSize = MapUtils.getInteger(map, "pageSize");
        }
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageNum = MapUtils.getInteger(map, "pageNum") * pageSize;
        }
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        Integer total = tbBizPlaceOrderManagerMapper.countGetTicketDetail(map);
        List<RespPlaceTicketDetail>  ticketDetailList = tbBizPlaceOrderManagerMapper.getTicketDetail(map);
        BigDecimal amountSum=new BigDecimal(0);
        for (RespPlaceTicketDetail resp : ticketDetailList){
            if(resp.getCreateUid()!=null&&resp.getCreateUid()!=0){
                TbAdminUser user = cacheService.getAdminUser(resp.getCreateUid());
                if(user!=null){
                    resp.setCreateName(user.getTrueName());
                }
            }
            if(resp.getSourceType()==1){
                String itemUuid = resp.getItemUuid();
                TbBizPlacePayItemExample example = new TbBizPlacePayItemExample();
                example.createCriteria().andOrderItemUuidEqualTo(itemUuid);
                List<TbBizPlacePayItem> payItems = tbBizPlacePayItemMapper.selectByExample(example);
                for (TbBizPlacePayItem payItem:payItems){
                    if(payItem.getPayType()==7){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount().divide(new BigDecimal(10))));
                    }
                    if(payItem.getPayType()==11){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount()));
                    }
                }
            }
            if(resp.getBusinessType()!=null){
                if(resp.getBusinessType()==1){
                    amountSum = amountSum.subtract(resp.getAmount());
                }else{
                    amountSum = amountSum.add(resp.getAmount());
                }
            }
        }
        RespPlaceTicketDetailSum sum = new RespPlaceTicketDetailSum();
        sum.setRespPlaceTicketDetailList(ticketDetailList);
        Integer ticketCountSum = tbBizPlaceOrderManagerMapper.getTicketDetailCountSum(map);
//        BigDecimal amountSum = tbBizPlaceOrderManagerMapper.getTicketDetailAmountSum(map);
        sum.setAmountSum(amountSum);
        sum.setTicketCountSum(ticketCountSum);
        sum.setLimit("说明："+limitDate+"之前下的订单数据不支持查询");
        PageObj<RespPlaceTicketDetailSum> result = PageObj.create(total, reqPageNum, pageSize, sum);
        return  APIResponse.returnSuccess(result);
    }

    /**
     * 门票销售明细导出
     *
     * @param map
     * @return
     */
    public APIResponse<RespPlaceTicketDetailSum> getTicketDetailExport(@Param("map") Map<String, Object> map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        map.put("pageNum",null);
        map.put("pageSize",null);
        List<RespPlaceTicketDetail>  ticketDetailList = tbBizPlaceOrderManagerMapper.getTicketDetailExport(map);
        BigDecimal amountSum=new BigDecimal(0);
        for (RespPlaceTicketDetail resp : ticketDetailList){
            if(resp.getCreateUid()!=null&&resp.getCreateUid()!=0){
                TbAdminUser user = cacheService.getAdminUser(resp.getCreateUid());
                if(user!=null){
                    resp.setCreateName(user.getTrueName());
                }
            }
            if(resp.getSourceType()==1){
                String itemUuid = resp.getItemUuid();
                TbBizPlacePayItemExample example = new TbBizPlacePayItemExample();
                example.createCriteria().andOrderItemUuidEqualTo(itemUuid);
                List<TbBizPlacePayItem> payItems = tbBizPlacePayItemMapper.selectByExample(example);
                for (TbBizPlacePayItem payItem:payItems){
                    if(payItem.getPayType()==7){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount().divide(new BigDecimal(10))));
                    }
                    if(payItem.getPayType()==11){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount()));
                    }
                }
            }
            if(resp.getBusinessType()!=null){
                if(resp.getBusinessType()==1){
                    amountSum = amountSum.subtract(resp.getAmount());
                }else{
                    amountSum = amountSum.add(resp.getAmount());
                }
            }
            resp.setCouponDiscount(PlaceUtil.isEmpty(resp.getDiscountCoupon()).add(PlaceUtil.isEmpty(resp.getDiscountDiscountCoupon())));
            resp.setMemberDiscount(PlaceUtil.isEmpty(resp.getDiscountMember()).add(PlaceUtil.isEmpty(resp.getDiscountDiscountMember())).add(PlaceUtil.isEmpty(resp.getDiscountNumberMember())));
        }
        RespPlaceTicketDetailSum sum = new RespPlaceTicketDetailSum();
        sum.setRespPlaceTicketDetailList(ticketDetailList);
        Integer ticketCountSum = tbBizPlaceOrderManagerMapper.getTicketDetailCountSum(map);
//        BigDecimal amountSum = tbBizPlaceOrderManagerMapper.getTicketDetailAmountSum(map);
        sum.setAmountSum(amountSum);
        sum.setTicketCountSum(ticketCountSum);
        sum.setLimit("说明："+limitDate+"之前下的订单数据不支持查询");
        return  APIResponse.returnSuccess(sum);
    }

    /**
     * 门票销售统计  --按门票编号
     * @param map
     * @return
     */
    public APIResponse<?> getTicketStatisticsByTicketCode(@Param("map") Map<String, Object> map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer reqPageNum = MapUtils.getInteger(map, "pageNum");
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageSize = MapUtils.getInteger(map, "pageSize");
        }
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageNum = MapUtils.getInteger(map, "pageNum") * pageSize;
        }
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        List<RespTicketStatisticsTicketCode>  respTicketCode = tbBizPlaceOrderManagerMapper.getTicketStatisticsByTicketCode(map);
        Integer total = tbBizPlaceOrderManagerMapper.countGetTicketStatisticsByTicketCode(map);
        RespTicketStatisticsTicketCodeSum sum = new RespTicketStatisticsTicketCodeSum();
        Integer ticketCountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailCountSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailAmountSum(map);
        List<RespTicketStatisticsTicketCode> respTicketCodeNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseCountProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespTicketStatisticsTicketCode rep : respTicketCode) {
            index++;
            BigDecimal countTemp = ticketCountTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getTicketCountSum()).divide(new BigDecimal(ticketCountTotal),4, RoundingMode.HALF_EVEN);
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setTicketCountProportion(dt.format(countTemp));
            if (index == respTicketCode.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setTicketCountProportion(dt.format(totalProportion.subtract(laseCountProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseCountProportion = laseCountProportion.add(countTemp);
            }
            if(ticketCountTotal==0){
                rep.setTicketCountProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respTicketCodeNew.add(rep);
        }
        sum.setRespTicketCode(respTicketCodeNew);
        sum.setTicketCountTotal(ticketCountTotal);
        sum.setAmountTotal(amountTotal);
        PageObj<RespTicketStatisticsTicketCodeSum> result = PageObj.create(total, reqPageNum, pageSize, sum);
        return APIResponse.returnSuccess(result);
    }

    /**
     * 门票销售统计  --按门票编号(导出)
     * @param map
     * @return
     */
    public APIResponse<?> getTicketStatisticsByTicketCodeExport(@Param("map") Map<String, Object> map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespTicketStatisticsTicketCode>  respTicketCode = tbBizPlaceOrderManagerMapper.getTicketStatisticsByTicketCode(map);
        RespTicketStatisticsTicketCodeSum sum = new RespTicketStatisticsTicketCodeSum();
        Integer ticketCountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailCountSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailAmountSum(map);
        List<RespTicketStatisticsTicketCode> respTicketCodeNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseCountProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespTicketStatisticsTicketCode rep : respTicketCode) {
            index++;
            BigDecimal countTemp = ticketCountTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getTicketCountSum()).divide(new BigDecimal(ticketCountTotal),4, RoundingMode.HALF_EVEN);
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setTicketCountProportion(dt.format(countTemp));
            if (index == respTicketCode.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setTicketCountProportion(dt.format(totalProportion.subtract(laseCountProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseCountProportion = laseCountProportion.add(countTemp);
            }
            if(ticketCountTotal==0){
                rep.setTicketCountProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respTicketCodeNew.add(rep);
        }
        sum.setRespTicketCode(respTicketCodeNew);
        sum.setTicketCountTotal(ticketCountTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

    /**
     * 门票销售统计  --按销售渠道
     * @param map
     * @return
     */
    public APIResponse<?> getTicketStatisticsByOrderChannel(@Param("map") Map<String, Object> map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespTicketStatisticsOrderChannel> respOrderChannel = tbBizPlaceOrderManagerMapper.getTicketStatisticsByOrderChannel(map);
        RespTicketStatisticsOrderChannelSum sum = new RespTicketStatisticsOrderChannelSum();
        Integer ticketCountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailCountSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailAmountSum(map);
        List<RespTicketStatisticsOrderChannel> respOrderChannelNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseCountProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespTicketStatisticsOrderChannel rep : respOrderChannel) {
            index++;
            BigDecimal countTemp = ticketCountTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getTicketCountSum()).divide(new BigDecimal(ticketCountTotal),4, RoundingMode.HALF_EVEN);
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setTicketCountProportion(dt.format(countTemp));
            if (index == respOrderChannel.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setTicketCountProportion(dt.format(totalProportion.subtract(laseCountProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseCountProportion = laseCountProportion.add(countTemp);
            }
            if(ticketCountTotal==0){
                rep.setTicketCountProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respOrderChannelNew.add(rep);
        }
        sum.setRespOrderChannel(respOrderChannelNew);
        sum.setTicketCountTotal(ticketCountTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

    /**
     * 门票销售统计  --按运动类型
     * @param map
     * @return
     */
    public APIResponse<?> getTicketStatisticsByCategory(@Param("map") Map<String, Object> map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespTicketStatisticsCategory> respCategory = tbBizPlaceOrderManagerMapper.getTicketStatisticsByCategory(map);
        RespTicketStatisticsCategorySum sum = new RespTicketStatisticsCategorySum();
        Integer ticketCountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailCountSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailAmountSum(map);
        List<RespTicketStatisticsCategory> respCategoryNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseCountProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespTicketStatisticsCategory rep : respCategory) {
            index++;
            BigDecimal countTemp = ticketCountTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getTicketCountSum()).divide(new BigDecimal(ticketCountTotal),4, RoundingMode.HALF_EVEN);
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setTicketCountProportion(dt.format(countTemp));
            if (index == respCategory.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setTicketCountProportion(dt.format(totalProportion.subtract(laseCountProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseCountProportion = laseCountProportion.add(countTemp);
            }
            if(ticketCountTotal==0){
                rep.setTicketCountProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respCategoryNew.add(rep);
        }
        sum.setRespCategory(respCategoryNew);
        sum.setTicketCountTotal(ticketCountTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

    /**
     * 门票销售统计  --按散客门票
     * @param map
     * @return
     */
    public APIResponse<?> getTicketStatisticsByMember(@Param("map") Map<String, Object> map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespTicketStatisticsMember> respMember = tbBizPlaceOrderManagerMapper.getTicketStatisticsByMember(map);
        RespTicketStatisticsMemberSum sum = new RespTicketStatisticsMemberSum();
        Integer ticketCountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailCountSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getTicketDetailAmountSum(map);
        List<RespTicketStatisticsMember> respMemberNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseCountProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespTicketStatisticsMember rep : respMember) {
            index++;
            BigDecimal countTemp = ticketCountTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getTicketCountSum()).divide(new BigDecimal(ticketCountTotal),4, RoundingMode.HALF_EVEN);
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setTicketCountProportion(dt.format(countTemp));
            if (index == respMember.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setTicketCountProportion(dt.format(totalProportion.subtract(laseCountProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseCountProportion = laseCountProportion.add(countTemp);
            }
            if(ticketCountTotal==0){
                rep.setTicketCountProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respMemberNew.add(rep);
        }
        sum.setRespMember(respMemberNew);
        sum.setTicketCountTotal(ticketCountTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

	
	

	
}
